import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { fetchGetVrs } from '@/api/create'
import type { SelectMtEntity } from '@/components/AddMt/translator/selected'
import { UserEntity } from '@/api/create/interface'
import Alert from '@/components/Alert'
import { t } from 'i18next'

export type RecorderMtEntity = {
	/**旧字段：enableLive、enableVideo 释义：录像模式。1-录像；2-直播；3-录像+直播 */
	recorder_mode: number
	/**旧字段：noLogin  释义：是否免登录观看直播 */
	anonymous: 0 | 1
	/**旧字段：doubleFlow  释义：是否开启双流 */
	dual_stream: 0 | 1
	/**旧字段：email  释义：邮件通知 */
	email: 0 | 1
	/**旧字段：publish  释义：发布模式 */
	publish_mode: 0 | 1
	/**旧字段：sms  释义：短信通知 */
	sms: 0 | 1
	/**旧字段：vrsId  释义：录播服务器唯一标识 */
	vrs_id: string
	/**旧字段：wechat  释义：微信通知 */
	wechat: 0 | 1
	/**旧字段：livePassword  释义：直播密码 */
	live_password: string
	/**直播人员 */
	live_members: Array<UserEntity>
}
type StateStore = {
	user: any
	/**直播开关 */
	enable_live: boolean
	/**录像开关*/
	enable_video: boolean
	vrsIdList: Array<{ label: string; value: string }>
	isShowVrsList: boolean
} & RecorderMtEntity

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	/**初始化数据*/
	init: (_data: null | RecorderMtEntity) => void
	/**清空直播成员列表 */
	clearUserList: () => void
	/**预留提供一个check函数，专门对该页面上的数据进行验证处理 */
	checkData: () => boolean
	getLiveMembersForAddModal: () => Array<{
		account: string
		accountType?: number
		name: string
		portrait: string
	}>
	/**获取参数 */
	getVideoLiveData: () => RecorderMtEntity | undefined
	/**改变录像 */
	changeEnableLive: (flag: boolean) => void
	/**处理选中的数据 */
	reviseUser: (d: Array<SelectMtEntity>) => SelectMtEntity[]
}

const initialState: StateStore = {
	user: null,
	vrs_id: '',
	publish_mode: 0,
	dual_stream: 1,
	anonymous: 0,
	live_members: [],
	email: 1,
	sms: 0,
	wechat: 0,
	live_password: '',
	/**直播开关 */
	enable_live: false,
	/**录像开关*/
	enable_video: false,
	vrsIdList: [],
	isShowVrsList: false,
	recorder_mode: 0,
}

export const useMeetingLiveVideoStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		/**初始化界面 */
		init: async (_data) => {
			if (_data) {
				const {
					recorder_mode,
					publish_mode = 0,
					dual_stream = 0,
					anonymous = 0,
					live_password = '',
					live_members = [],
					email,
					sms,
					wechat,
				} = _data
				set({
					enable_live: recorder_mode === 2 || recorder_mode === 3, // 录像模式。1-录像；2-直播；3-录像+直播
					enable_video: recorder_mode === 1 || recorder_mode === 3,
					live_password: live_password,
					publish_mode: publish_mode,
					dual_stream: dual_stream,
					anonymous: anonymous,
					live_members: live_members,
					email,
					sms,
					wechat,
				})
			}
			const res: any = await fetchGetVrs()
			if (res.success && res.list) {
				let result: Array<{ label: string; value: string }> =
					res.list?.map(
						(item: { network_name: string; server_name: string; server_typ: string; vrs_id: string }) => {
							return { label: item.server_name, value: item.vrs_id }
						}
					) || []
				let flag = result.findIndex((item) => item.value === _data?.vrs_id)
				if (flag !== -1) {
					set({ vrs_id: _data?.vrs_id, vrsIdList: result })
				} else {
					set({ vrs_id: result[0]?.value ?? '', vrsIdList: result })
				}
				result.length > 1 ? set({ isShowVrsList: true }) : set({ isShowVrsList: false })
			} else {
				set({ isShowVrsList: false })
			}
		},
		changeEnableLive: (flag) => {
			set({ enable_live: flag })
			if (!flag) {
				set({ live_password: '' })
			}
		},
		reviseUser: (mtList) => {
			var meetingName = ''
			for (var i = 0; i < mtList.length; i++) {
				if (mtList[i].accountType === 2) {
					meetingName = mtList[i].name ?? ''
					if (i + 1 < mtList.length) {
						for (var j = i + 1; j < mtList.length; ) {
							if (mtList[j].accountType === 2 && meetingName === mtList[j].name) {
								mtList.splice(j, 1)
							} else {
								j++
							}
						}
					}
				}
			}
			return mtList
		},
		getVideoLiveData: () => {
			const {
				enable_live,
				enable_video,
				live_password,
				email,
				dual_stream,
				anonymous,
				publish_mode,
				sms,
				wechat,
				vrs_id,
				live_members,
			} = get()
			const _live_members = live_members
				.filter((item) => {
					return item
				})
				.map((item) => {
					return {
						name: item.name, // 名称
						account: item.account, // 帐号
						account_type: item.account_type, // 帐号类型 1-moid；4-非系统邮箱；5-e164号；6-电话；7-ip地址；8-别名@ip(监控前端)
						conf_e164: item.parent_id ?? '',
					}
				})
			let _recorder_mode = 0
			if (enable_live && enable_video) {
				_recorder_mode = 3
			} else if (enable_live && !enable_video) {
				_recorder_mode = 2
			} else if (!enable_live && enable_video) {
				_recorder_mode = 1
			}
			if (_recorder_mode === 0) {
				return undefined
			} else {
				return {
					anonymous: anonymous,
					dual_stream: dual_stream,
					live_password: live_password,
					live_members: _live_members, // 直播人员通知列表
					publish_mode: publish_mode,
					recorder_mode: _recorder_mode,
					email: email,
					sms: sms,
					wechat: wechat,
					vrs_id: vrs_id, // 录播服务器唯一标识
				}
			}
		},
		//获取人员列表
		getLiveMembersForAddModal: () => {
			const { live_members } = get()
			let result = live_members.map((item) => {
				return {
					account: item.account ?? '',
					accountType: item.account_type,
					name: item.name ?? '',
					portrait: item.portrait ?? '',
				}
			})
			return result
		},
		clearUserList: function () {
			set({ live_members: [] })
		},
		checkData: () => {
			const { enable_live, enable_video, vrsIdList, live_password, vrs_id } = get()
			if (enable_live || enable_video) {
				if (vrsIdList.length === 0) {
					Alert(t('录播服务器故障，请联系管理员'))
					return false
				} else if (vrs_id === '') {
					Alert(t('请选择录播服务器'))
					return false
				}
			}
			if (enable_live && live_password.length !== 0) {
				if (enable_live && !/^[a-zA-Z0-9]*$/.test(live_password)) {
					Alert(t('直播密码存在非法字符,请重新输入'))
					return false
				}
				if (enable_live && !/^([a-zA-Z0-9]{6})$/.test(live_password)) {
					Alert(t('直播密码输入错误'))
					return false
				}
			}
			return true
		},
	}))
)
